package com.wwwarehouse.common.activity.base;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.alibaba.android.arouter.launcher.ARouter;
import com.wei.android.lib.fingerprintidentify.FingerprintIdentify;
import com.wei.android.lib.fingerprintidentify.base.BaseFingerprint;
import com.wwwarehouse.common.R;
import com.wwwarehouse.common.common.Common;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.common.tools.ProgressDialogUtils;
import com.wwwarehouse.common.tools.SharedPreferencesHelper;
import com.wwwarehouse.common.tools.ToastUtils;

import java.util.ArrayList;
import java.util.Random;

public class BaseActivity extends AppCompatActivity {
    public SharedPreferencesHelper sp = null;
    public Context mContext;
    ProgressDialogUtils progressDialogUtils = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        if (Build.VERSION.SDK_INT >= 19) {
            // 设置沉浸式
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // android:background="@color/white_color"
            // android:clipToPadding="true"
            // android:fitsSystemWindows="true"
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }

        Common.getInstance().addActivity(this);

        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        sp = BaseApplication.sp;
        mContext = this;

        try {
            // 设置小米和魅族手机的状态栏变灰
            BaseApplication.getApplicationInstance().setStatusDark(this, true);
        } catch (Exception e) {

        }

    }


    public void onResume() {
        super.onResume();

    }

    private FingerprintIdentify mFingerprintIdentify;
    private boolean             mIsFingerStarted;
    public void onEvent(String string) {
        if ("FINGER".equals(string)) {
            //登入状态
            String sp_token = sp.getValue(Constant.sp_Token);
            //指纹
            mFingerprintIdentify = new FingerprintIdentify(BaseApplication.getApplicationInstance(), new BaseFingerprint.FingerprintIdentifyExceptionListener() {
                @Override
                public void onCatchException(Throwable exception) {
                    LogUtils.showLog(exception.getLocalizedMessage());
                }
            });
            //是否开启指纹验证存
            mIsFingerStarted = BaseApplication.getApplicationInstance().sp.getBooleanValue("sp_finger", false);
            if (!TextUtils.isEmpty(sp_token) && mIsFingerStarted && mFingerprintIdentify.isHardwareEnable()) {
                //跳activity
                startActivity(Constant.PATH_FINGERLOGIN_ACTIVITY, null, false);
            }
        }
    }


    public void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Common.getInstance().removeActivity(this);
    }

    // 代替findViewById
    public <T extends View> T findView(int id) {
        return (T) findViewById(id);
    }

    // 弹出Toast
    public void toastAtTop(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtils.showToastAtTop(msg);
            }
        });
    }

    public void toastAtTop(final int resource) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtils.showToastAtTop(resource);
            }
        });
    }

    // 弹出Toast
    public void toast(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtils.showToast(msg);
            }
        });
    }

    public void toast(final int resource) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtils.showToast(resource);
            }
        });
    }

    // 打开一个Activity传递一个Bundle
    public void startActivity(Class<? extends Activity> target, Bundle bundle, boolean finish) {
        if (Common.getInstance().isNotFastClick()) {
            Intent intent = new Intent(this, target);
            if (bundle != null) {
                intent.putExtras(bundle);
            }

            startActivity(intent);
            overridePendingTransition(R.anim.comm_slide_in_from_right, R.anim.comm_scale_out);
            if (finish) {
                finish();
            }
        }
    }

    public void startActivity(String target, Bundle bundle, boolean finish) {

        if(target == null || "".equals(target)){
            if(LogUtils.isDebug()){
                toast(getString(R.string.arouter_mistake));
            }
            return ;
        }

        ARouter.getInstance()
                .build(target)
                .with(bundle)
                .withTransition(R.anim.comm_slide_in_from_right, R.anim.comm_scale_out)
                .navigation(this);

        if (finish) {
            finish();
        }
    }

    // 打开一个Activity传递一个字符串
    public void startActivity(Class<? extends Activity> target, String passDataKey, String value, boolean finish) {
        if (Common.getInstance().isNotFastClick()) {
            Intent intent = new Intent(this, target);
            if (passDataKey != null && value != null) {
                intent.putExtra(passDataKey, value);
            }
            startActivity(intent);
            overridePendingTransition(R.anim.comm_slide_in_from_right, R.anim.comm_scale_out);
            if (finish) {
                finish();
            }
        }
    }

    // 打开一个Activity传递一个boolean类型
    public void startActivity(Class<? extends Activity> target, String passDataKey, boolean value, boolean finish) {
        if (Common.getInstance().isNotFastClick()) {
            Intent intent = new Intent(this, target);
            if (passDataKey != null) {
                intent.putExtra(passDataKey, value);
            }
            startActivity(intent);
            overridePendingTransition(R.anim.comm_slide_in_from_right, R.anim.comm_scale_out);
            if (finish) {
                finish();
            }
        }
    }

    // 打开一个Activity传递一个ArrayList
    public void startActivity(Class<? extends Activity> target, String passDataKey, ArrayList<String> list, boolean finish) {
        if (Common.getInstance().isNotFastClick()) {
            Intent intent = new Intent(this, target);
            if (passDataKey != null) {
                intent.putStringArrayListExtra(passDataKey, list);
            }
            startActivity(intent);
            overridePendingTransition(R.anim.comm_slide_in_from_right, R.anim.comm_scale_out);
            if (finish) {
                finish();
            }
        }
    }

    // 打开一个Activity
    public void startActivityForResult(Class<? extends Activity> target, int requestCode, Bundle bundle) {
        if (Common.getInstance().isNotFastClick()) {
            Intent intent = new Intent(this, target);
            if (bundle != null) {
                intent.putExtras(bundle);
            }
            startActivityForResult(intent, requestCode);
            overridePendingTransition(R.anim.comm_slide_in_from_right, R.anim.comm_scale_out);
        }
    }

    public void startActivityForResult(String target, Bundle bundle, int requestCode) {

        if (target == null || "".equals(target)){
            if(LogUtils.isDebug()){
                toast(getString(R.string.arouter_mistake));
            }
            return ;
        }

        ARouter.getInstance()
                .build(target)
                .with(bundle)
                .withTransition(R.anim.comm_slide_in_from_right, R.anim.comm_scale_out)
                .navigation(this, requestCode);
    }

    // 获取上个界面传过来的Bundle
    public Bundle getBundle() {
        try {
            Intent it = getIntent();
            if (it != null && it.getExtras() != null) {
                return it.getExtras();
            }
        } catch (Exception e) {

        }

        return null;
    }

    public void finishActivity() {
        finish();
        overridePendingTransition(R.anim.comm_scale_in, R.anim.comm_slide_out_to_right);
    }

    public void finishActivityForResult(int resultCode, Bundle bundle) {
        Intent intent1 = new Intent();
        if (bundle != null)
            intent1.putExtras(bundle);
        setResult(resultCode, intent1);
        finish();
        overridePendingTransition(R.anim.comm_scale_in, R.anim.comm_slide_out_to_right);
    }

    public void finishActivityForResult(int resultCode) {
        finishActivityForResult(resultCode, null);
    }

    // 隐藏软键盘
    public void hideSoftKeyBoard(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //隐藏键盘
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    // 显示软键盘
    public void showSoftKeyBoard(View view) {
        view.requestFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //显示键盘
        imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
    }

    // 保存到剪切板
    public void saveToClipboard(String text) {
        ClipboardManager c = (ClipboardManager) getSystemService(Service.CLIPBOARD_SERVICE);
        c.setText(text);
        toast("已复制到剪切板");
    }

    //获取随机数， 参数为返回随机数的长度
    public String generateRandomString(int length) {
        String allChar = "0123456789abcdefghijklmnopqrstuvwxyz";
        StringBuffer sb = new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            sb.append(allChar.charAt(random.nextInt(allChar.length())));
        }
        return sb.toString();
    }

    // 显示ProgressDialog
    public void showProgressDialog() {
        progressDialogUtils = ProgressDialogUtils.show(mContext);
    }

    // 显示ProgressDialog
    public void showProgressDialog(String text) {
        progressDialogUtils = ProgressDialogUtils.show(mContext,text);
    }

    // 隐藏ProgressDialog
    public void dismissProgress() {
        if (progressDialogUtils != null && progressDialogUtils.isShowing()) {
            progressDialogUtils.dismiss();
        }
    }

    //改变progress上文字
    public void setProgressDialogText(String text){
        if (progressDialogUtils != null){
            progressDialogUtils.setTextHint(text);
        }
    }

    public Display getScreenParams() {
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        return display;
    }

    public interface OnBackListener {
        boolean onBack();

    }

    //region软键盘的处理

    /**------------------------------------------隐藏软件盘的代码段starting-----------------------------------------------*/
    /**
     * 清除editText的焦点
     * @param v   焦点所在View
     * @param ids 输入框
     */
    private void clearViewFocus(View v, int... ids) {
        if (null != v && null != ids && ids.length > 0) {
            for (int id : ids) {
                if (v.getId() == id) {
                    v.clearFocus();
                    break;
                }
            }
        }
    }

    /**
     * 隐藏键盘
     * @param v   焦点所在View
     * @param ids 输入框
     * @return true代表焦点在edit上
     */
    private boolean isFocusEditText(View v, int... ids) {
        if (v instanceof EditText) {
            EditText tmp_et = (EditText) v;
            for (int id : ids) {
                if (tmp_et.getId() == id) {
                    return true;
                }
            }
        }
        return false;
    }

    //是否触摸在指定view上面,对某个控件过滤
    private boolean isTouchView(View[] views, MotionEvent ev) {
        if (views == null || views.length == 0)
            return false;
        int[] location = new int[2];
        for (View view : views) {
            view.getLocationOnScreen(location);
            int x = location[0];
            int y = location[1];
            if (ev.getX() > x && ev.getX() < (x + view.getWidth())
                    && ev.getY() > y && ev.getY() < (y + view.getHeight())) {
                return true;
            }
        }
        return false;
    }

    //是否触摸在指定view上面,对某个控件过滤
    private boolean isTouchView(int[] ids, MotionEvent ev) {
        int[] location = new int[2];
        for (int id : ids) {
            View view = findViewById(id);
            if (view == null)
                continue;
            view.getLocationOnScreen(location);
            int x = location[0];
            int y = location[1];
            if (ev.getX() > x && ev.getX() < (x + view.getWidth())
                    && ev.getY() > y && ev.getY() < (y + view.getHeight())) {
                return true;
            }
        }
        return false;
    }
    //endregion

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            if (isTouchView(arrayViews, ev))
                return super.dispatchTouchEvent(ev);
            if (arrayInt == null || arrayInt.length == 0)
                return super.dispatchTouchEvent(ev);
            View v = getCurrentFocus();

            if (isFocusEditText(v, arrayInt)) {
                //是否是可以touche事件
                if (isTouchView(arrayInt, ev))
                    return super.dispatchTouchEvent(ev);
                //隐藏键盘
                hideInputForce(this);
                //清除掉焦点事件
                clearViewFocus(v, arrayInt);

            }
        }
        return super.dispatchTouchEvent(ev);

    }

    int[]  arrayInt;
    View[] arrayViews;
    /**
     * 传入EditText的Id
     * 没有传入的EditText不做处理
     * @return id 数组
     */
    public void hideSoftByEditViewIds(int[] array) {
        arrayInt = array;
    }

    /**
     * 传入要过滤的View
     * 过滤之后点击将不会有隐藏软键盘的操作
     * @return id 数组
     */
    public void filterViewByIds(View[] array) {
        arrayViews = array;
    }

    /**
     * des:隐藏软键盘,这种方式参数为activity
     * @param activity
     */
    protected void hideInputForce(Activity activity) {
        if (activity == null || activity.getCurrentFocus() == null)
            return;
        ((InputMethodManager) activity.getSystemService(INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(activity.getCurrentFocus()
                        .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }


    /**------------------------------------------隐藏软件盘的代码段ending-------------------------------------------*/
}
